package com.xj.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.xj.utils.DatabaseInfo;

public class PropertiesConfig {
    public static Properties prop = new Properties();

    static {
        loadConfig();
    }

    public static void loadConfig(){
        InputStream input = null;
        try {
            input = PropertiesConfig.class.getClassLoader().getResourceAsStream("application.properties");
            prop.load(input);
        } catch (IOException e) {
            System.out.println("配置文件读取失败..." + e.getMessage());
            e.printStackTrace();
        }
    }

    public static Properties getPropertiesConfig() {
        return prop;
    }

    public static String getPropertiesConfigValue(String key) {
        return prop.getProperty(key);
    }

    public static List<DatabaseInfo> getPropertiesConfigDBs() {
        List<DatabaseInfo> databaseInfoList = new ArrayList<>();
        String[] list = prop.getProperty("source.database").split(",");
        if(list != null && list.length > 0){
            Arrays.asList(list).stream()
                .forEach((daName) -> {
                    String tablesStr = getPropertiesConfigValue("source.database." + daName + ".tables");
                    List<String> tableList = null;
                    if(tablesStr != null){
                        String[] tables = tablesStr.split(",");
                        tableList = Arrays.asList(tables);
                    }
                    databaseInfoList.add(new DatabaseInfo(daName, tableList));
                });
        }
        return databaseInfoList;
    }
}
